/********************************************************************************
*
*
*  This program is demonstration for ellipse fitting. Program finds
*  contours and approximate it by ellipses.
*
*  Trackbar specify threshold parametr.
*
*  White lines is contours. Red lines is fitting ellipses.
*
*
*  Autor:  Denis Burenkov.
*
*
*
********************************************************************************/
#include "cvxImage.h"
#include <iostream>
using namespace cv;
using namespace std;

void help()
{
	cout <<
			"\nThis program is demonstration for ellipse fitting. The program finds\n"
			"contours and approximate it by ellipses.\n"
			"Call:\n"
			"./fitellipse [image_name -- Default stuff.jpg]\n" << endl;
}

int sliderPos = 70;

Mat image;

void processImage(int, void*);

// int main( int argc, char** argv )
// {
//     const char* filename = argc == 2 ? argv[1] : (char*)"stuff.jpg";
//     image = imread(filename, 0);
//     if( image.empty() )
//     {
//         cout << "Couldn't open image " << filename << "\nUsage: fitellipse <image_name>\n";
//         return 0;
//     }
// 
//     imshow("source", image);
//     namedWindow("result", 1);
//     
//     // Create toolbars. HighGUI use.
//     createTrackbar( "threshold", "result", &sliderPos, 255, processImage );
//     processImage(0, 0);
// 
//     // Wait for a key stroke; the same function arranges events processing
//     waitKey();
//     return 0;
// }
#if 0
int main(int argc, char** argv)
{
	IplImage *image = cvLoadImage("org.png", 1);
	IplImage *gray  = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
	cvCvtColor(image, gray, CV_BGR2GRAY);
	// smooth it, otherwise a lot of false circles may be detected
	cvSmooth( gray, gray);
	vector<Vec3f> circles;
// 	CVAPI(CvSeq*) cvHoughCircles( CvArr* image, void* circle_storage,
// 		int method, double dp, double min_dist,
// 		double param1 CV_DEFAULT(100),
// 		double param2 CV_DEFAULT(100),
// 		int min_radius CV_DEFAULT(0),
// 		int max_radius CV_DEFAULT(0));
	HoughCircles(Mat(gray), circles, CV_HOUGH_GRADIENT,
				 2, gray->width/2, 100, 50 );
	for( size_t i = 0; i < circles.size(); i++ )
	{
		Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
		int radius = cvRound(circles[i][2]);
		// draw the circle center
		cvCircle( image, center, 3, Scalar(0,255,0), -1, 8, 0 );
		// draw the circle outline
		cvCircle( image, center, radius, Scalar(0,0,255), 3, 8, 0 );
	}
	namedWindow( "circles", 1 );
	cvShowImage( "circles", image );



	IplImage *imageA = cvLoadImage("org_single_chessboard.png", 1);
	double tt = clock();
	vector<Point2f> centerPts;
	
	bool isOk = cv::findCirclesGrid(Mat(imageA), cvSize(1, 1), centerPts, CALIB_CB_SYMMETRIC_GRID);
	printf("1.375 in cost time = %f\n", clock()-tt);
	if (isOk)
	{
		cv::drawChessboardCorners(Mat(imageA), cvSize(1, 1), centerPts, true);
		cvShowImage("1.375 circles center", imageA);		
	}

	imageA = cvLoadImage("org_single_chessboard.png", 1);
	tt = clock();
	centerPts.clear();
	isOk = cv::findChessboardCorners(Mat(imageA), cvSize(15, 9), centerPts);

	if (isOk)
	{
		cv::drawChessboardCorners(Mat(imageA), cvSize(15, 9), centerPts, true);
	}	
	cvShowImage("find4QuadCornerSubpix center", imageA);	

	cvWaitKey(0);
	return 0;
}
#endif


// Define trackbar callback functon. This function find contours,
// draw it and approximate it by ellipses.
void processImage(int /*h*/, void*)
{
    vector<vector<Point> > contours;
    Mat bimage = image >= sliderPos;
    
    findContours(bimage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);

    Mat cimage = Mat::zeros(bimage.size(), CV_8UC3);

    for(size_t i = 0; i < contours.size(); i++)
    {
        size_t count = contours[i].size();
        if( count < 6 )
            continue;
        
        Mat pointsf;
        Mat(contours[i]).convertTo(pointsf, CV_32F);
        RotatedRect box = fitEllipse(pointsf);
        
        if( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*30 )
            continue;
        drawContours(cimage, contours, (int)i, Scalar::all(255), 1, 8);

        ellipse(cimage, box, Scalar(0,0,255), 1, CV_AA);
        ellipse(cimage, box.center, box.size*0.5f, box.angle, 0, 360, Scalar(0,255,255), 1, CV_AA);
        Point2f vtx[4];
        box.points(vtx);
        for( int j = 0; j < 4; j++ )
            line(cimage, vtx[j], vtx[(j+1)%4], Scalar(0,255,0), 1, CV_AA);
    }

    imshow("result", cimage);
}
